package com.atguigu.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.SkuHasStockVo;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.order.constant.OrderConstant;
import com.atguigu.gulimall.order.entity.OrderItemEntity;
import com.atguigu.gulimall.order.entity.OrderReturnReasonEntity;
import com.atguigu.gulimall.order.enume.OrderStatusEnum;
import com.atguigu.gulimall.order.feign.CartFeignService;
import com.atguigu.gulimall.order.feign.MemberFeignService;
import com.atguigu.gulimall.order.feign.ProductFeignService;
import com.atguigu.gulimall.order.feign.WmsFeignService;
import com.atguigu.gulimall.order.intercepctor.LoginUserInterceptor;
import com.atguigu.gulimall.order.vo.*;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.nio.channels.Channel;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.order.dao.OrderDao;
import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.service.OrderService;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.annotation.Resource;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {


    @Resource
    private ProductFeignService productFeignService;

    @Resource
    private CartFeignService cartFeignService;

    @Resource
    private MemberFeignService memberFeignService;

    @Resource
    private WmsFeignService wmsFeignService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    
    @Resource
    ThreadPoolExecutor threadPoolExecutor;


    private ThreadLocal<OrderSubmitVo> confirmVoThreadLocal   = new ThreadLocal<>();

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 跳转结算确认页面
     * @return
     */
    @Override
     public OrderConfirmVo toTrade() throws ExecutionException, InterruptedException {
        OrderConfirmVo orderConfirmVo = new OrderConfirmVo();
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();

        // 获取当前线程请求头信息（防止feign异步调用时，请求头丢失）
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        //1. 异步查询购物车商品
        CompletableFuture<Void> cartInfoFuture  = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<OrderItemVo> currentCartItems = cartFeignService.getCurrentCartItems();
            orderConfirmVo.setItems(currentCartItems);
        }, threadPoolExecutor);
        //2. 异步查询收货地址
        CompletableFuture<Void> addressFuture   = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
//            List<MemberAddressVo> memberAddressVoList = memberFeignService.getAddress(memberRespVo.getId());
            List<MemberAddressVo> memberAddressVoList = memberFeignService.getAddress(1L);
            orderConfirmVo.setMemberAddressVos(memberAddressVoList);
        }, threadPoolExecutor).thenRunAsync(() -> {
            //3. 异步查询库存
            RequestContextHolder.setRequestAttributes(requestAttributes);
//            List<OrderItemVo> items = orderConfirmVo.getItems();
//            List<Long> skuIds = items.stream().map(item -> {
//                return item.getSkuId();
//            }).collect(Collectors.toList());
            R skuHasStock = wmsFeignService.getSkuHasStock(Arrays.asList(3L));
            List<SkuStockVo> skuStockVos = skuHasStock.getData("data", new TypeReference<List<SkuStockVo>>() {
            });
            Map<Long, Boolean> collect = skuStockVos.stream().collect(Collectors.toMap(SkuStockVo::getSkuId, SkuStockVo::getHasStock));
            orderConfirmVo.setStocks(collect);
        }, threadPoolExecutor);

        //4. 异步查询积分
//        Integer integration = memberRespVo.getIntegration();
//        orderConfirmVo.setIntegration(integration);

        orderConfirmVo.setIntegration(5166);


        CompletableFuture.allOf(cartInfoFuture,addressFuture).get();
        // 5 .生成token
        String token = UUID.randomUUID().toString().replace("-", "");
//        stringRedisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX+memberRespVo.getId().toString()
//                             ,token,30, TimeUnit.MINUTES);
        stringRedisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX+1
                ,token,30, TimeUnit.MINUTES);
        orderConfirmVo.setOrderToken(token);

        return orderConfirmVo;
    }

    /**
     * 提交订单***
     * @param orderSubmitVo
     * @return
     */
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo orderSubmitVo) {
        confirmVoThreadLocal.set(orderSubmitVo);
        SubmitOrderResponseVo response = new SubmitOrderResponseVo();
//        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        response.setCode(0);
        //1、验证令牌【令牌的对比和删除必须保证原子性】
        //0令牌失败 - 1删除成功
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        String orderToken = orderSubmitVo.getOrderToken();
        //原子验证令牌和删除令牌
//        Long result = stringRedisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class)
//                , Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId()), orderToken);
        Long result = stringRedisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class)
                , Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX +1), orderToken);
        if (result == 0L) {
            //令牌验证失败
            response.setCode(1);
            return response;
        } else{
            //TODO：令牌校验成功，去创建订单，校验价格，锁库存
            //1、创建订单，订单项等信息
            OrderCreateTo order = createOrder();
            response.setOrder(order.getOrder());
            return response;
        }
//        return null;
    }



    private OrderCreateTo createOrder(){
        OrderCreateTo orderCreateTo = new OrderCreateTo();
        // 1. 构造订单信息
        OrderEntity orderEntity=this.buildOrder();
        // 2. 构造订单项****
        List<OrderItemEntity> orderItemEntities = this.builderOrderItems(orderEntity.getOrderSn());

        //验价(计算价格、积分等信息)
        this.compute(orderEntity,orderItemEntities);
        orderCreateTo.setOrder(orderEntity);
        orderCreateTo.setOrderItems(orderItemEntities);
        return orderCreateTo;
    }

    /**
     *  3. 验价(计算价格、积分等信息)
     * @param orderEntity
     * @param itemEntityList
     */
    private void compute(OrderEntity orderEntity, List<OrderItemEntity> itemEntityList) {
        //总价
        BigDecimal total = new BigDecimal("0.0");
        //优惠价
        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal intergration = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");
        //积分、成长值
        Integer integrationTotal = 0;
        Integer growthTotal = 0;

        //订单总额，叠加每一个订单项的总额信息
        for (OrderItemEntity orderItem : itemEntityList) {
            //优惠价格信息
            coupon = coupon.add(orderItem.getCouponAmount());
            promotion = promotion.add(orderItem.getPromotionAmount());
            intergration = intergration.add(orderItem.getIntegrationAmount());
            //总价
            total = total.add(orderItem.getRealAmount());
            //积分信息和成长值信息
            integrationTotal += orderItem.getGiftIntegration();
            growthTotal += orderItem.getGiftGrowth();
        }
        //1、订单价格相关的
        orderEntity.setTotalAmount(total);
        //设置应付总额(总额+运费)
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        orderEntity.setCouponAmount(coupon);
        orderEntity.setPromotionAmount(promotion);
        orderEntity.setIntegrationAmount(intergration);
        //设置积分成长值信息
        orderEntity.setIntegration(integrationTotal);
        orderEntity.setGrowth(growthTotal);
        //设置删除状态(0-未删除，1-已删除)
        orderEntity.setDeleteStatus(0);

    }

    /**
     * 2. 构造订单项****
     * @param orderSn
     * @return
     */
    private List<OrderItemEntity> builderOrderItems(String orderSn){
        List<OrderItemEntity> orderItemEntityList = new ArrayList<>();
        List<OrderItemVo> currentCartItems = cartFeignService.getCurrentCartItems();
        if(currentCartItems!=null && currentCartItems.size()>0){
            orderItemEntityList = currentCartItems.stream().map(item -> {
                OrderItemEntity orderItemEntity = builderOrderItem(item);
                orderItemEntity.setOrderSn(orderSn);
                return orderItemEntity;
            }).collect(Collectors.toList());
        }
        return orderItemEntityList;
    }

    private OrderItemEntity builderOrderItem(OrderItemVo item) {
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        R r = productFeignService.getSpuInfoBySkuId(item.getSkuId());
        SpuInfoVo spuInfoVo = r.getData("data", new TypeReference<SpuInfoVo>() {
        });

        // 1. 获取spu信息
        orderItemEntity.setSpuId(spuInfoVo.getId());
        orderItemEntity.setCategoryId(spuInfoVo.getCatalogId());
        orderItemEntity.setSpuBrand(spuInfoVo.getBrandName());
        orderItemEntity.setSpuName(spuInfoVo.getSpuName());
        // 2. 获取sku信息
        orderItemEntity.setSkuId(item.getSkuId());
        orderItemEntity.setSkuName(item.getTitle());
        orderItemEntity.setSkuPic(item.getImage());
        orderItemEntity.setSkuPrice(item.getPrice());
        orderItemEntity.setSkuQuantity(item.getCount());

        //使用StringUtils.collectionToDelimitedString将list集合转换为String
        String skuAttr = StringUtils.collectionToDelimitedString(item.getSkuAttrValues(), ";");
        orderItemEntity.setSkuAttrsVals(skuAttr);
        //3、商品的优惠信息

        //4、商品的积分信息
        orderItemEntity.setGiftGrowth(item.getPrice().multiply(new BigDecimal(item.getCount())).intValue());
        orderItemEntity.setGiftIntegration(item.getPrice().multiply(new BigDecimal(item.getCount())).intValue());

        //5、订单项的价格信息
        orderItemEntity.setPromotionAmount(BigDecimal.ZERO);
        orderItemEntity.setCouponAmount(BigDecimal.ZERO);
        orderItemEntity.setIntegrationAmount(BigDecimal.ZERO);

        //6、当前订单项的实际金额.总额 - 各种优惠价格
//        原来价格
        BigDecimal origin = orderItemEntity.getSkuPrice().multiply(
                new BigDecimal(orderItemEntity.getSkuQuantity().toString()));
        //原价减去优惠价得到最终的价格
        BigDecimal finalPrice = origin.subtract(orderItemEntity.getPromotionAmount())
                .subtract(orderItemEntity.getCouponAmount())
                .subtract(orderItemEntity.getIntegrationAmount());
        orderItemEntity.setRealAmount(finalPrice);

        return orderItemEntity;
    }


    /**
     * 1. 构建订单信息***
     * @return
     */
    private OrderEntity buildOrder(){

        OrderEntity orderEntity = new OrderEntity();
        String orderSn = IdWorker.getTimeId();
        orderEntity.setOrderSn(orderSn);

//        OrderSubmitVo orderSubmitVo = confirmVoThreadLocal.get();
//        Long addrId = orderSubmitVo.getAddrId();
//        R r = wmsFeignService.getFare(addrId);
        R r = wmsFeignService.getFare(2L);
        AddrAndFareVo addrAndFareVo = r.getData("data", new TypeReference<AddrAndFareVo>() {
        });

        orderEntity.setFreightAmount(new BigDecimal(addrAndFareVo.getFare()));
        orderEntity.setReceiverName(addrAndFareVo.getMemberAddressVo().getName());
        orderEntity.setReceiverProvince(addrAndFareVo.getMemberAddressVo().getProvince());
        orderEntity.setReceiverCity(addrAndFareVo.getMemberAddressVo().getCity());
        orderEntity.setReceiverDetailAddress(addrAndFareVo.getMemberAddressVo().getDetailAddress());
        orderEntity.setReceiverPostCode(addrAndFareVo.getMemberAddressVo().getPostCode());
        orderEntity.setReceiverPhone(addrAndFareVo.getMemberAddressVo().getPhone());
        orderEntity.setReceiverRegion(addrAndFareVo.getMemberAddressVo().getRegion());

        //设置订单相关的状态信息
        orderEntity.setAutoConfirmDay(7);
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        orderEntity.setConfirmStatus(0);
        return orderEntity;
    }

//    @RabbitListener(queues = {"hello-queue"})
//    public void receive(Message message, OrderReturnReasonEntity entity) {
//        byte[] body = message.getBody();
//        Class<? extends Message> aClass = message.getClass();
//
//        System.out.println("消息体："+body+"类型"+aClass+"收到消息：" + entity);
//    }

    @RabbitListener(queues = {"hello-queue"})
    public void receiveMessage(Message message, OrderReturnReasonEntity entity, Channel channel) {
        byte[] body = message.getBody();
        MessageProperties messageProperties = message.getMessageProperties();
        System.out.println("接收到消息...内容：" + entity);
        System.out.println("消息处理完成" + entity.getName());
    }


}